import os, pickle, numpy

def Unpickle(indir, infile, outdir, outfile, plotter, argn):
    f = open(os.path.join(indir, infile+'.pck'),'r')
    Unpickler = pickle.Unpickler(f)
    args = []
    for i in range(argn):
        args.append(Unpickler.load())
    f.close()
    plotter(*args, repickle=False, outdir=outdir, outfile=outfile)

def Repickle(outdir, outfile, *args):
    f = open(os.path.join(outdir, outfile+'.pck'), 'w')
    pickler = pickle.Pickler(f)
    for list in args:
        pickler.dump(list)
    f.close()
    
def Polyfit(x, y, degree=1):
    results = {}

    coeffs = numpy.polyfit(x, y, degree)

    # Polynomial Coefficients
    results['poly'] = coeffs.tolist()

    # r-squared
    p = numpy.poly1d(coeffs)
    # fit values, and mean
    yhat = [p(z) for z in x]
    ybar = sum(y)/len(y)
    ssreg = sum([ (yihat - ybar)**2 for yihat in yhat])
    sstot = sum([ (yi - ybar)**2 for yi in y])
    results['det'] = ssreg / sstot

    return results

class Plotter(object):
    def __setattr__(self, name, value):
        try:
            self.attrs[name] = value
        except AttributeError:
            super(Plotter,self).__setattr__('attrs', {})
            self.attrs[name] = value
        super(Plotter,self).__setattr__(name, value)